﻿using System.ComponentModel;

namespace Utility
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举描述值
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <returns></returns>
        public static string GetDescription(this System.Enum value)
        {
            var fi = value.GetType().GetField(value.ToString());
            var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : string.Empty;
        }

        /// <summary>
        /// 根据枚举值获取名称
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetName<T>(int value)
        {
            string name = System.Enum.Parse(typeof(T), System.Enum.GetName(typeof(T), value)??string.Empty).ToString() ?? string.Empty;
            return name;
        }

        /// <summary>
        /// 根据描述获取枚举下标
        /// </summary>
        /// <typeparam name="T">枚举</typeparam>
        /// <param name="type">类型</param>
        /// <param name="descriptionValue">描述值</param>
        /// <returns></returns>
        public static int GetValueByDescription<T>(this Type type, string descriptionValue) where T : struct
        {
            var enumValue = 0;
            foreach (var value in System.Enum.GetValues(type))
            {
                var attribute = typeof(T).GetField(value.ToString() ?? string.Empty).GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attribute != null && ((DescriptionAttribute)attribute[0]).Description == descriptionValue)
                {
                    enumValue = Convert.ToInt32(value);
                }
            }
            return enumValue;
        }
    }
}
